package com.hmall.trade.listener;

import com.hmall.api.item.ItemClient;
import com.hmall.api.item.dto.OrderDetailDTO;
import com.hmall.api.pay.PayClient;
import com.hmall.api.pay.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @Author mr.zhao
 * @Date 2025/6/23 17:42
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderDelayMessageListener {

	private final IOrderService orderService;
	private final IOrderDetailService orderDetailService;
	private final PayClient payClient;
	private final ItemClient itemClient;

	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
			exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
			key = MqConstants.DELAY_ORDER_KEY
	))
	public void listenOrderDelayMessage(Long orderId){
		log.info("[订单Id]: {}",orderId);
		//1. 查询订单
		Order order = orderService.getById(orderId);
		//2. 检测订单状态,判读是否已支付
		if (order == null || order.getStatus() != 1){
			// 订单不存在或则已经支付
			return;
		}
		//3.未支付,需要查询支付流水状态
		// PayOrder payOrder = payOrderService.lambdaQuery().eq(PayOrder::getBizOrderNo, order.getId()).one();
		PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(order.getId());
		log.info("[支付流域水状态]: {}",payOrderDTO);


		//4. 判断是否支付
		if (payOrderDTO.getStatus() == 3){
			//4.1 已支付,标记订单状态为已支付
			orderService.markOrderPaySuccess(orderId);
		}else {
			//4.2 未支付,取消订单,回滚库存
			//取消订单
			order.setStatus(5);
			orderService.updateById(order);
			//回滚库存
			OrderDetail orderDetail = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, order.getId()).one();
			OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
			BeanUtils.copyProperties(orderDetail, orderDetailDTO);
			log.info("[回滚库存]: {}",orderDetailDTO);
			itemClient.rollbackStock(orderDetailDTO);
		}


	}
}
